#!/bin/bash
sdcard=$1
create=1
if [ "$(id -u)" != "0" ]; then
   echo "Script must be run as root !"
   exit 0
fi

if [  "$(fdisk -l $sdcard)" == "" ]
then
	echo "sdcard dev not found!!!"
	exit 0
fi
boot_size=${OPI_SDCARD_BOOT_SIZE}
boot_start=${OPI_SDCARD_BOOT_START}
sdcard_sectors=`fdisk -l $sdcard | grep "Disk $sdcard" | awk '{print $7}'`
sdcard_bytes=`fdisk -l $sdcard | grep "Disk $sdcard" | awk '{print $5}'`
sdcard_block=$(expr $sdcard_bytes / $sdcard_sectors )
block_size=$(expr 1024 \* 1024 / $sdcard_block )
sdcard_size=$(expr $sdcard_bytes / 1024 / 1024 )
root_size=$(expr  $sdcard_size - $boot_size - $(expr $boot_start / $block_size ) )
boot_end=$(expr $boot_start + $(expr $boot_size \* $block_size ) - 1)
root_start=$(expr $boot_end + 1)
root_end=$(expr $(expr $root_size \* $block_size ) + $root_start - 1 )


echo ""
echo " sdcard dev :   $sdcard"
echo " sdcard total size   :  $sdcard_size	M"
echo " boot partition size :  $boot_size	M"
echo " root partition size :  $root_size	M"
echo " boot start : $boot_start"
echo " boot end   : $boot_end"
echo " root start : $root_start"
echo " root end   : $root_end"
echo ""








# Create the disk and partition it
# We start out at around 3MB so there is room to write u-boot without issues.
echo "Creating image file for NanoPi2"
dd if=/dev/zero of=${basedir}/kali-$1-nanopi2.img bs=1M count=7000
parted kali-$1-nanopi2.img --script -- mklabel msdos
parted kali-$1-nanopi2.img --script -- mkpart primary ext4 3072s 264191s
parted kali-$1-nanopi2.img --script -- mkpart primary ext4 264192s 100%

# Set the partition variables
loopdevice=`losetup -f --show ${basedir}/kali-$1-nanopi2.img`
device=`kpartx -va $loopdevice| sed -E 's/.*(loop[0-9])p.*/\1/g' | head -1`
sleep 5
device="/dev/mapper/${device}"
bootp=${device}p1
rootp=${device}p2

# Create file systems
mkfs.ext4 $bootp
mkfs.ext4 $rootp

# Create the dirs for the partitions and mount them
mkdir -p ${basedir}/bootp ${basedir}/root
mount $bootp ${basedir}/bootp
mount $rootp ${basedir}/root

echo "Rsyncing rootfs into image file"
rsync -HPavz -q ${basedir}/kali-$architecture/ ${basedir}/root/

# Serial console settings.
# (No auto login)
echo 'T1:12345:respawn:/sbin/agetty 115200 ttyAMA0 vt100' >> ${basedir}/root/etc/inittab

cat << EOF > ${basedir}/root/etc/apt/sources.list
deb http://http.kali.org/kali kali-rolling main non-free contrib
deb-src http://http.kali.org/kali kali-rolling main non-free contrib
EOF

# Uncomment this if you use apt-cacher-ng otherwise git clones will fail.
#unset http_proxy

# Kernel section. If you want to use a custom kernel, or configuration, replace
# them in this section.
git clone --depth 1 https://github.com/friendlyarm/linux-3.4.y -b nanopi2-lollipop-mr1 ${basedir}/root/usr/src/kernel
cd ${basedir}/root/usr/src/kernel
git rev-parse HEAD > ../kernel-at-commit
touch .scmversion
export ARCH=arm
export CROSS_COMPILE=arm-linux-gnueabihf-
patch -p1 --no-backup-if-mismatch < ${basedir}/../patches/mac80211.patch
# Ugh, this patch is needed because the ethernet driver uses parts of netdev
# from a newer kernel?
patch -p1 --no-backup-if-mismatch < ${basedir}/../patches/0001-Remove-define.patch
cp ${basedir}/../kernel-configs/nanopi2* ..
cp ../nanopi2-720p.config .config
make -j $(grep -c processor /proc/cpuinfo)
make uImage
make modules_install INSTALL_MOD_PATH=${basedir}/root
# We copy this twice because you can't do symlinks on fat partitions.
# Also, the uImage known as uImage.hdmi is used by uboot if hdmi output is
# detected.
cp arch/arm/boot/uImage ${basedir}/bootp/uImage-720p
cp arch/arm/boot/uImage ${basedir}/bootp/uImage.hdmi
# Friendlyarm suggests staying at 720p for now.
cp ../nanopi2-1080p.config .config
make -j $(grep -c processor /proc/cpuinfo)
make uImage
cp arch/arm/boot/uImage ${basedir}/bootp/uImage-1080p
cp ../nanopi2-lcd-hd101.config .config
make -j $(grep -c processor /proc/cpuinfo)
make uImage
cp arch/arm/boot/uImage ${basedir}/bootp/uImage-hd101
cp ../nanopi2-lcd-hd700.config .config
make -j $(grep -c processor /proc/cpuinfo)
make uImage
cp arch/arm/boot/uImage ${basedir}/bootp/uImage-hd700
cp ../nanopi2-lcd.config .config
make -j $(grep -c processor /proc/cpuinfo)
make uImage
# The default uImage is for lcd usage, so we copy the lcd one twice
# so people have a backup in case they overwrite uImage for some reason.
cp arch/arm/boot/uImage ${basedir}/bootp/uImage-s70
cp arch/arm/boot/uImage ${basedir}/bootp/uImage.lcd
cp arch/arm/boot/uImage ${basedir}/bootp/uImage
make mrproper
cp ../nanopi2-720p.config .config
make modules_prepare
cd ${basedir}

rm -rf ${basedir}/root/lib/firmware
cd ${basedir}/root/lib
git clone https://git.kernel.org/pub/scm/linux/kernel/git/firmware/linux-firmware.git firmware
rm -rf ${basedir}/root/lib/firmware/.git
mkdir -p ${basedir}/root/lib/firmware/ap6212/
wget https://raw.githubusercontent.com/friendlyarm/android_vendor_broadcom_nanopi2/nanopi2-lollipop-mr1/proprietary/nvram_ap6212.txt -O ${basedir}/root/lib/firmware/ap6212/nvram.txt
wget https://raw.githubusercontent.com/friendlyarm/android_vendor_broadcom_nanopi2/nanopi2-lollipop-mr1/proprietary/fw_bcm43438a0.bin -O ${basedir}/root/lib/firmware/ap6212/fw_bcm43438a0.bin
wget https://raw.githubusercontent.com/friendlyarm/android_vendor_broadcom_nanopi2/nanopi2-lollipop-mr1/proprietary/fw_bcm43438a0_apsta.bin -O ${basedir}/root/lib/firmware/ap6212/fw_bcm43438a0_apsta.bin
wget https://raw.githubusercontent.com/friendlyarm/android_vendor_broadcom_nanopi2/nanopi2-lollipop-mr1/proprietary/bcm43438a0.hcd -O ${basedir}/root/lib/firmware/ap6212/bcm43438a0.hcd
cd ${basedir}

cp ${basedir}/../misc/zram ${basedir}/root/etc/init.d/zram
chmod +x ${basedir}/root/etc/init.d/zram

# Unmount partitions
umount $bootp
umount $rootp
kpartx -dv $loopdevice

# Samsung bootloaders must be signed.
# These are the same steps that are done by
# https://github.com/friendlyarm/sd-fuse_nanopi2/blob/master/fusing.sh
dd if=${basedir}/../misc/nanopi2/2ndboot.bin of=$loopdevice bs=512 seek=1
dd if=${basedir}/../misc/nanopi2/boot.TBI of=$loopdevice bs=512 seek=64 count=1
dd if=${basedir}/../misc/nanopi2/bootloader of=$loopdevice bs=512 seek=65
sync

cd ${basedir}

losetup -d $loopdevice

# Clean up all the temporary build stuff and remove the directories.
# Comment this out to keep things around if you want to see what may have gone
# wrong.
echo "Clean up the build system"
rm -rf ${basedir}/bootp ${basedir}/root ${basedir}/kali-$architecture ${basedir}/patches

# If you're building an image for yourself, comment all of this out, as you
# don't need the sha1sum or to compress the image, since you will be testing it
# soon.
echo "Generating sha1sum for kali-$1-nanopi2.img"
sha1sum kali-$1-nanopi2.img > ${basedir}/kali-$1-nanopi2.img.sha1sum











read -p "Will clear the SD card data, whether or not to continue ?[y/n]"  continue
if [ "$continue" == "y" ];then
	mount_dev=`mount | grep $sdcard | awk '{print $3}'`
	umount -f $mount_dev
	echo ""
	echo -e "d\n\nd\n\nd\n\nd\n\nw\n" | fdisk $sdcard > /dev/null 
	#echo " dd sdcard........"
	#dd if=/dev/zero of=$sdcard  count=1

	echo "fdisk sdcard..........."
	echo -e "n\np\n1\n${boot_start}\n${boot_end}\nt\nb\nw\n" | fdisk $sdcard 
	echo -e "n\np\n2\n${root_start}\n${root_end}\nw\n" | fdisk $sdcard  
	fdisk -l $sdcard
	echo ""

	check_boot=`fdisk -l $sdcard | grep $sdcard"1" | awk '{print $2}'`
	check_root=`fdisk -l $sdcard | grep $sdcard"2" | awk '{print $2}'`

	if [[ $check_boot == $boot_start  && $check_root == $root_start ]];then
		echo "mkfs image............"
		sleep 3
		mkfs.vfat $sdcard"1"
		sleep 3
		dosfslabel $sdcard"1" "BOOT"
		sleep 3
		mkfs.ext4 $sdcard"2"
		sleep 3
		e2label $sdcard"2" "ROOTFS"
		echo ""
	fi
else 
	echo "exit"
	exit 0
fi


#mount partition
sleep 1
mkdir -p $OPI_SDCARD_BOOT $OPI_SDCARD_ROOT
echo "mount -t vfat $sdcard"1" $OPI_SDCARD_BOOT"
mount -t vfat $sdcard"1" $OPI_SDCARD_BOOT
sleep 1
echo "mount -t ext4 $sdcard"2" $OPI_SDCARD_ROOT"
mount -t ext4 $sdcard"2" $OPI_SDCARD_ROOT

#read -p "Enter any key, close to mount :"
#fuser -ck $OPI_SDCARD_BOOT
#fuser -ck $OPI_SDCARD_ROOT
#umount -f $OPI_SDCARD_BOOT
#umount -f $OPI_SDCARD_ROOT
#echo "umount :$OPI_SDCARD_BOOT"
#echo "umount :$OPI_SDCARD_ROOT"

echo ""
echo "^_^"
